package org.example.com.editor.command.editorCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.command.Undoable;
import org.example.com.editor.command.commandHistory.CommandHistoryItem;
import org.example.com.editor.editor.Editor;
import org.example.com.editor.editor.TextEditor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DeleteCommand implements Command, Undoable {
    private final LogManager logManager;

    public DeleteCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        if (editor == null) {
            ui.printError("没有活动文件，请先打开或新建文件");
            return;
        }

        String[] args = ui.getCommandArgs();
        if (args.length != 3) {
            ui.printError("用法：delete <行号:列号> <长度>（例如：delete 1:1 5）");
            return;
        }

        // 解析行号和列号
        String[] lineCol = args[1].split(":", 2);
        if (lineCol.length != 2) {
            ui.printError("位置格式错误，请使用\"行号:列号\"（例如：1:1）");
            return;
        }

        int lineNum, colNum, length;
        try {
            lineNum = Integer.parseInt(lineCol[0]);
            colNum = Integer.parseInt(lineCol[1]);
            length = Integer.parseInt(args[2]);
        } catch (NumberFormatException e) {
            ui.printError("行号、列号和长度必须是整数");
            return;
        }

        try {
            // 关键：执行删除前获取原行长度（避免行被移除后无法获取）
            String targetLine = editor.getContent().get(lineNum - 1);
            int originalLineLength = targetLine.length();

            // 执行删除
            String deletedText = editor.delete(lineNum, colNum, length);

            // 完整存储所有需要的参数（Key名称与undo/redo时一致）
            Map<String, Object> params = new HashMap<>();
            params.put("deletedText", deletedText);
            params.put("lineNum", lineNum);
            params.put("colNum", colNum);
            params.put("length", length); // 存储length供redo使用
            params.put("originalLineLength", originalLineLength); // 存储原行长度

            editor.recordCommand(new CommandHistoryItem(this, params));
        } catch (IllegalArgumentException e) {
            ui.printError("[ERROR] 执行命令失败：" + e.getMessage());
        }catch (IndexOutOfBoundsException e) {
            // 兜底捕获索引越界（防止极端情况）
            ui.printError("[ERROR] 执行命令失败：位置越界");
        }

        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void undo(Editor editor, ConsoleUI ui, Map<String, Object> params) {
        // 空值校验：避免Key缺失导致null
        Integer lineNum = (Integer) params.get("lineNum");
        Integer colNum = (Integer) params.get("colNum");
        String deletedText = (String) params.get("deletedText");
        Integer originalLineLength = (Integer) params.get("originalLineLength");

        if (lineNum == null || colNum == null || deletedText == null || originalLineLength == null) {
            ui.printError("撤销删除操作失败：参数不完整");
            return;
        }

        ((TextEditor) editor).undoDelete(lineNum, colNum, deletedText, originalLineLength);
    }

    @Override
    public void redo(Workspace workspace, ConsoleUI ui, Map<String, Object> params) {
        // redo从params取参，而非成员变量（成员变量可能为空）
        Integer lineNum = (Integer) params.get("lineNum");
        Integer colNum = (Integer) params.get("colNum");
        Integer length = (Integer) params.get("length");

        if (lineNum == null || colNum == null || length == null) {
            ui.printError("重做删除操作失败：参数不完整");
            return;
        }

        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        if (editor != null) {
            editor.delete(lineNum, colNum, length);
        }
    }

    @Override
    public String getName() {
        return "delete";
    }
}